import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import akka.actor.ActorRef;
import static akka.actor.Actors.*;

/**
 *  Grep files for lines matching a pattern
 * 
 *  Re-implementation using Actors
 *
 */
public class CGrep {

	/**
	 * Runs parameterized CGrep, printing results when complete
	 * @param args
	 * 		0 regex pattern to match
	 * 		1 file path in which to run grep
	 */
	public static void main(String[] args) {
		// Exit if no regex or file provided
		if( args.length == 0 ) {
			System.exit(1);
		}

		List<String> files = new ArrayList<String>();
		if(args.length < 2) {		
			// Add indicator for stdin
			files.add("-");	
		} else {
			// Add specified filenames to list
			for( int i = 1; i < args.length; i++) {
				files.add(args[i]);
			}
		}

		// Read in & compile provided regex
		Pattern pattern = Pattern.compile(args[0]);
		
		// Create FileCount message
		FileCount fileCount = new FileCount(files.size());
		
		// Create a CollectionActor & start it
		ActorRef collectionActor = actorOf(CollectionActor.class).start();
		collectionActor.tell(fileCount);
		
		// Create, configure, & start ScanActors for each file
		for (String file : files) {
			Configure conf = new Configure(file, collectionActor, pattern);
			ActorRef scanActor = actorOf(ScanActor.class).start();
			scanActor.tell(conf);
		}
	}
}
